const Service = require('egg').Service;

class HomeService extends Service {
  // 加入购物车
  async addToCart() {
    const {ctx,app} = this;
    const {user_id,shop_id} = ctx.request.body;
    const isHave = await app.mysql.get('carts', {user_id,shop_id})
    let data;
    if(isHave) {
      data = await app.mysql.update('carts', {id:isHave.id,count: isHave.count+=1})
    } else {
      data = await app.mysql.insert('carts', {user_id,shop_id,count:1})
    }
    return data;
  }
  async getCartList() {
    const {ctx,app} = this;
    // 获取购物车列表的思路
    const {user_id} = ctx.request.body;
    const data = await app.mysql.select('carts', {user_id})
    const pAll = data.map(item=> {
      return app.mysql.get('shops',{id: item.shop_id})
    })
    const shopData = await Promise.all(pAll)
    const newData  =data.map((item,index) => {
      return {...shopData[index],...item}
    })
    return newData
  }
  async setCartCount() {
  }
  async delCart() {
  }
}

module.exports = HomeService;